'use strict';

const JWT = require('jsonwebtoken');


const middleware = (options) => {
    let defaults = {
        verifyFuntional: null,
        secretOrPublicKey: '',
        token: '',
        query: 'token'
    };

    options = Object.assign(defaults, options);

    function disconnect(socket) {
        socket.disconnect();
    }

    const verify = socket => {
        let token = options.token !== '' ? options.token : socket.handshake.query[options.query];
        if (typeof options.verifyFuntional === 'function') {
            options.verifyFuntional(token, (err) => {
                if (err) {
                    disconnect(socket);
                }
            });
        } else {
            if (options.secretOrPublicKey){
                let result = JWT.verify(token, options.secretOrPublicKey);
                if (!result) disconnect(socket);
            } else {
                throw new Error('Not found secretOrPublicKey.');
            }
        }
    };

    return verify;
};

module.exports = exports = middleware;
